package info.empathymobile.monitor.business;

import info.empathymobile.monitor.business.beans.MonitorEntry;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.BatteryManager;

import com.j256.ormlite.dao.RuntimeExceptionDao;

public class MonitorBO {

	private Context context;
	private RuntimeExceptionDao<MonitorEntry, Integer> monitorEntryDao = null;

	public MonitorBO(Context context){
		this.context = context;
		this.monitorEntryDao = ((OrmLiteBase<DatabaseHelper>)context).getHelper().getMonitorEntryDao();
	}
	
	public MonitorBO(Context context, RuntimeExceptionDao<MonitorEntry, Integer> monitorEntryDao){
		this.context = context;
		this.monitorEntryDao = monitorEntryDao;
	}

	public void saveMonitorEntry(MonitorEntry monitorEntry){
		this.monitorEntryDao.create(monitorEntry);
	}
	
	public int deleteMonitorEntriesById(ArrayList<Integer> monitorEntriesId){
		return this.monitorEntryDao.deleteIds(monitorEntriesId);
	}
	
	public List<MonitorEntry> getAllMonitorEntries(){
		return this.monitorEntryDao.queryForAll();
	}
	
    public MonitorEntry getBatteryStatus(){
    	Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    	
    	MonitorEntry batteryEntry = new MonitorEntry();
    	
    	batteryEntry.setType(intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1));
    	batteryEntry.setLogClass(MonitorEntry.BATTERY_ENTRY_LOG_CLASS);
    	batteryEntry.setStatus(intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1));
    	
        return batteryEntry;
    }
    
	public MonitorEntry getConnectivityStatus() {
		ConnectivityManager cm = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

		MonitorEntry connectivityEntry = new MonitorEntry();
		connectivityEntry.setLogClass(MonitorEntry.CONNECTIVITY_ENTRY_LOG_CLASS);
		
		if(activeNetwork != null && activeNetwork.isAvailable() && activeNetwork.isConnected()){
			connectivityEntry.setStatus(MonitorEntry.CONNECTIVITY_ENTRY_NET_CONNECTED);
			connectivityEntry.setType(activeNetwork.getType());
		}
		else {
			connectivityEntry.setStatus(MonitorEntry.CONNECTIVITY_ENTRY_NET_DISCONNECTED);
		}
			
		return connectivityEntry;
	}
}
